package de.sendorian.app.forumArchive.matcher;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import de.sendorian.util.matcher.BlacklistMatcher;


public class FileBlackilistMatcher extends BlacklistMatcher<String> {

	private static final Logger LOG = Logger.getLogger(FileBlackilistMatcher.class);

	private ResourceLoader resourceLoader;


	public FileBlackilistMatcher(String fileName) {
		List<String> unwantedStringsMatcher = new ArrayList<String>();

		try {
			File file = getResourceLoader().getResource(fileName).getFile();
			Scanner scanner = new Scanner(file);
			try {
				while (scanner.hasNextLine()) {
					unwantedStringsMatcher.add(scanner.nextLine());
				}
			} finally {
				scanner.close();
			}
		} catch (IOException e) {
			LOG.error("Could not open blacklist " + fileName, e);
		}

		setUnwantedObjects(unwantedStringsMatcher);
	}


	@Override
	protected boolean matchesInternal(String objectToCompare, Object unwantedObject) {
		return StringUtils.contains(objectToCompare, (String) unwantedObject);
	}


	protected ResourceLoader getResourceLoader() {
		if (resourceLoader == null) {
			resourceLoader = new DefaultResourceLoader();
		}

		return resourceLoader;
	}

}
